#include "CliConn.hpp"

#include <cerrno>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <netinet/in.h>
#include <fcntl.h>
#include <string>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <iostream>
#include <vector>

#include "../../base/MessageUnti.hpp"

#include "../../base/MessageUnti.hpp"

#define LOG() printf("[log] %s : line(%d)\n", __FUNCTION__, __LINE__)

CliConn::CliConn(const char *ip, int port) {
    sock.sin_family = AF_INET;
    sock.sin_port = htons(port);
    sock.sin_addr.s_addr = inet_addr(ip);
    socklen_t len = sizeof(sock);
    if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
    {
        LOG();
        exit(1);
    }
    if (connect(fd, (struct sockaddr *)&sock, len) < 0)
    {
        LOG();
        exit(1);
    }
    //std::cout << "client fd(" << fd << ")\n";
}

CliConn::~CliConn() {
    close(fd);
}

using DBServer::Base::Unti::ClientStatusMachine;

void CliConn::echo(Msg &msg) {

    auto tuple = msg();

    send(this->fd, tuple.second, tuple.first, 0);
    //write(this->fd, tuple.second, tuple.first);

    char buffer[1024];

    std::vector<std::string> responds;
    ClientStatusMachine::analysis(this->fd, buffer, 1024, responds);

    //std::cout << "send : " << msg().second << std::endl;
    // std::cout << "recv : " << responds[0] << std::endl;
}
